import 'dart:convert';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/jiayouList_model.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/jiayouzhan/MapUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/SignUtil.dart';

import 'jyz_pay_page.dart';

class JYZDetailPage extends StatefulWidget {
  // String gasIds;
  JYZModelData model;
  JYZDetailPage({Key key, this.model}) : super(key: key);

  @override
  _JYZDetailPageState createState() => _JYZDetailPageState(model);
}

class _JYZDetailPageState extends State<JYZDetailPage> {
  // // 创建一个给native的channel (类似iOS的通知）
  static const methodChannel = const MethodChannel('com.pages.your/native_get');

  _iOSPushToVC(String url) async {
    await methodChannel.invokeMethod('iOSFlutter', url);
  }

  JYZModelData model;
  _JYZDetailPageState(this.model);

  // List list = [
  //   {"title": "影视特效", "type": 0,},
  //   {"title": "室内设计", "type": 1},
  //   {"title": "游戏原画", "type": 2},
  //   {"title": "次时代", "type": 3},
  //   {"title": "UI设计", "type": 4},
  //   {"title": "后期合成", "type": 5},
  // ];

  List oilPriceList = []; //油号
  int groupValue = 0;
  List gunNos = []; //油枪
  int gunValue = 0;

  var name;
  @override
  Widget build(BuildContext context) {
    // int groupValue=1;
    return Scaffold(
        appBar: AppBar(
            backgroundColor: mainColor,
            title: new Text(
              '加油站',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
            ),
            centerTitle: true,
            actions: <Widget>[
              new IconButton(
                  icon: new Icon(Icons.collections), onPressed: () {})
            ]),
        backgroundColor: Colors.white,
        body: Container(
            child: CustomScrollView(slivers: <Widget>[
          SliverToBoxAdapter(
            child: Container(
                // height: bannerHeight,
                child: Column(
              children: <Widget>[
                Card(
                  elevation: 5,
                  child: _buildListItem(),
                )
              ],
            )),
          ),
          SliverToBoxAdapter(
            child: Container(
                // height: bannerHeight,
                child: Column(
              children: <Widget>[
                Container(
                    margin: EdgeInsets.all(
                        ScreenUtil.getInstance().setHeight(DP_30)),
                    child: Text('选择油号'))
              ],
            )),
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (MediaQuery.of(context).size.width -
                      ScreenUtil.getInstance().setHeight(DP_30)) /
                  4,
              mainAxisSpacing: ScreenUtil.getInstance().setHeight(DP_30),
              crossAxisSpacing: ScreenUtil.getInstance().setHeight(DP_30),
              childAspectRatio: 2.6, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return listitem(context, index, 0);
              },
              childCount: oilPriceList.length,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
                // height: bannerHeight,
                child: Column(
              children: <Widget>[
                Container(
                    margin: EdgeInsets.all(
                        ScreenUtil.getInstance().setHeight(DP_30)),
                    child: Text('选择油枪'))
              ],
            )),
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (MediaQuery.of(context).size.width -
                      ScreenUtil.getInstance().setHeight(DP_30)) /
                  4,
              mainAxisSpacing: ScreenUtil.getInstance().setHeight(DP_30),
              crossAxisSpacing: ScreenUtil.getInstance().setHeight(DP_30),
              childAspectRatio: 2.6, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return listitem(context, index, 1);
              },
              childCount: gunNos.length,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
                // height: bannerHeight,
                child: Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Expanded(
                        child: Container(
                            height: MediaQuery.of(context).size.height * 0.06,
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_30),
                                ScreenUtil.getInstance().setHeight(DP_30) * 2,
                                ScreenUtil.getInstance().setHeight(DP_30),
                                0),
                            child: RaisedButton(
                              shape: RoundedRectangleBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)),
                              ),
                              //当前选中
                              color: mainColor,
                              onPressed: () {
                                //跳转支付页
                                var gasIds = this.model.gas_id;
                                getCode(name, gasIds, gunValue.toString());
                              },
                              child: Text(
                                '确认',
                                style: TextStyle(color: Colors.white),
                              ),
                            )))
                  ],
                ),
                Container(
                    margin: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_30),
                        ScreenUtil.getInstance().setHeight(DP_30),
                        ScreenUtil.getInstance().setHeight(DP_30),
                        ScreenUtil.getInstance().setHeight(DP_20)),
                    child: Text('若无您选择的油枪号，请联系油站工作人员')),
                Container(
                    margin: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_30),
                        0,
                        ScreenUtil.getInstance().setHeight(DP_30),
                        ScreenUtil.getInstance().setHeight(DP_30)),
                    child: Text('支付前请确认加油站是否正确'))
              ],
            )),
          ),
        ])));
  }

  getCode(String name, String gasId, String gun) async {
    Map map = new Map();
    map['phone'] = APPLIC.userInfoMap['user_msg']['phone'];
    Response<String> response = await HttpUtil().post(
        "https://mcs.czb365.com/services/v3/begin/getSecretCode",
        data: getSign2(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    Navigator.of(context).pop(1);
    if (code == 200 && mounted) {
      var url = "https://open.czb365.com/redirection/todo" +
          '?platformType=92655472&authCode=' +
          userMap['result'] +
          '&gasId=' +
          gasId +
          '&gunNo=' +
          gunValue.toString();
      Navigator.push(
          context,
          MaterialPageRoute(
              //导航打开新视图
              builder: (context) =>
                  JYZPayPage(url: url) //打开第二个页面，并传值，传递值的名称是model
              ));
    }
  }

  Widget listitem(context, index, type) {
    //0是油号 1是油枪
    var value = type == 0 ? oilPriceList[index] : gunNos[index];
    var deviceSize = MediaQuery.of(context).size;
    return type == 0
        ? (groupValue == value['oilNo']
            ? RaisedButton(
                shape: StadiumBorder(),
                //当前选中
                color: mainColor,
                onPressed: () {
                  print('切换${value}');
                  updateGroupValue(value['oilNo']);
                  print(value['gunNos']);
                  setState(() {
                    gunNos = value['gunNos'];
                    //  gunValue = gunNos[0]['gunNo'];
                  });
                },
                child: Text(
                  value['oilName'],
                  style: TextStyle(color: Colors.white),
                ),
              )
            : OutlineButton(
                shape: StadiumBorder(),
                onPressed: () {
                  print('切换${value}');
                  updateGroupValue(value['oilNo']);
                  print(value['gunNos']);
                  setState(() {
                    gunNos = value['gunNos'];
                    gunValue = gunNos[0]['gunNo'];
                  });
                },
                child: Text(value['oilName']),
              ))
        : (gunValue == value['gunNo']
            ? RaisedButton(
                shape: StadiumBorder(),
                color: mainColor,
                onPressed: () {
                  print('切换${value}');
                  updateGunValue(value['gunNo']);
                },
                child: Text(
                  value['gunNo'].toString(),
                  style: TextStyle(color: Colors.white),
                ),
              )
            : OutlineButton(
                shape: StadiumBorder(),
                onPressed: () {
                  print('切换${value}');
                  updateGunValue(value['gunNo']);
                },
                child: Text(value['gunNo'].toString()),
              ));
  }

  Widget _buildListItem() {
    return Container(
        margin: EdgeInsets.fromLTRB(0, ScreenUtil().setHeight(15), 0, 0),
        child: Column(
          children: <Widget>[
            Row(children: <Widget>[
              _leftImage(),
              Expanded(
                child: _rightColumn(),
              )
            ], crossAxisAlignment: CrossAxisAlignment.start),
            Divider(
              height: 1,
            )
          ],
        ));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(l) ?? 0,
            ScreenUtil().setHeight(t) ?? 0,
            ScreenUtil().setWidth(r) ?? 0,
            ScreenUtil().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage() {
    //左图
    var image = new Image(
        image: NetworkImage(model.gaslogosmall),
        width: ScreenUtil().setHeight(150),
        height: ScreenUtil().setHeight(150),
        fit: BoxFit.fill);
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn() {
    //右内容
    var title = Text(
      model.gas_name,
      style: TextStyle(color: Colors.black, fontSize: 16.0),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(text: model.priceyfq, style: TextStyle(fontSize: 18.0)),
        TextSpan(
            text: '/升/' + model.oil_name, style: TextStyle(fontSize: 12.0)),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: 13.0), children: [
        TextSpan(
            text: formatNum(double.parse(model.distance) / 1000, 2) + "km",
            style: TextStyle(color: Colors.grey)),
        TextSpan(text: '    导航', style: TextStyle(color: Colors.orange)),
      ]),
    );
    var address = Text(
      model.provincename + model.cityname + model.countyname + model.gasaddress,
      style: TextStyle(color: Colors.grey, fontSize: 13.0),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        Row(
          children: <Widget>[
            _pd(price, l: 10, t: 0, r: 10, b: 8),
            GestureDetector(
              child: distance,
              onTap: () async {
                var result = await showModalBottomSheet(
                    context: context,
                    builder: (context) {
                      return Container(
                        height:
                            // Platform.isIOS
                            //     ? ScreenUtil.getInstance().setHeight(DP_200 + 40) +
                            //         2
                            //     :
                            ScreenUtil.getInstance().setHeight(DP_160) +
                                1, //配置底部弹出框高度
                        child: Column(
                          children: <Widget>[
                            GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              child: Container(
                                height:
                                    ScreenUtil.getInstance().setHeight(DP_80),
                                alignment: Alignment.center,
                                child: Text('百度地图',
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                              ),
                              onTap: () {
                                Navigator.pop(context, '1');
                              },
                            ),
                            Container(
                              height: 1,
                              color: f0Color,
                            ),
                            GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              child: Container(
                                height:
                                    ScreenUtil.getInstance().setHeight(DP_80),
                                alignment: Alignment.center,
                                child: Text('高德地图',
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                              ),
                              onTap: () {
                                Navigator.pop(context, '2');
                              },
                            ),
                            // Offstage(
                            //   offstage: !Platform.isIOS,
                            //   child: Container(
                            //     height: 1,
                            //     color: f0Color,
                            //   ),
                            // ),
                            // Offstage(
                            //   offstage: !Platform.isIOS,
                            //   child: GestureDetector(
                            //     behavior: HitTestBehavior.opaque,
                            //     child: Container(
                            //       height:
                            //           ScreenUtil.getInstance().setHeight(DP_80),
                            //       alignment: Alignment.center,
                            //       child: Text('苹果地图',
                            //           style: TextStyle(
                            //               fontSize: ScreenUtil.getInstance()
                            //                   .setSp(NORMAL_FONT_SIZE))),
                            //     ),
                            //     onTap: () {
                            //       Navigator.pop(context, '3');
                            //     },
                            //   ),
                            // ),
                          ],
                        ),
                      );
                    });
                if ("1" == result) {
                  MapUtil.gotoBaiduMap(
                      model.gasaddresslongitude, model.gasaddresslatitude);
                } else if ("2" == result) {
                  MapUtil.gotoAMap(
                      model.gasaddresslongitude, model.gasaddresslatitude);
                }
                // else {
                //   MapUtil.gotoAppleMap(
                //       model.geo);
                // }
              },
            )
          ],
        ),
        _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  void updateGroupValue(int v) {
    setState(() {
      groupValue = v;
      print(v);
    });
  }

  void updateGunValue(int v) {
    setState(() {
      gunValue = v;
      print(v);
    });
  }

  @override
  void initState() {
    super.initState();
    getString(PHONE).then((value) {
      name = value;
      _getGasDetail(this.model.gas_id, value);
    });
  }

  // kGas_detailURL
  _getGasDetail(gasIds, phone) async {
    FormData data = new FormData.fromMap({'gasIds': gasIds, 'phone': phone});
    Response<String> response =
        await HttpUtil().post(Api.JIAYOU_DETAIL, data: data);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 0) {
      if (mounted) {
        List result = userMap['data']['list'];
        Map result1 = result[0];
        List theoilPriceList = result1['oilPriceList'];
        print(result[0]);
        setState(() {
          oilPriceList = theoilPriceList;
          groupValue = theoilPriceList[0]['oilNo'];
          gunNos = theoilPriceList[0]['gunNos'];
          gunValue = gunNos[0]['gunNo'];
        });
      }
    }
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }
}
